package com.ai3d.rfid.network.download

import com.ai3d.rfid.common.proxy.MMKVProxy
import com.ai3d.rfid.common.utils.HandlerUtils.post
import com.ai3d.rfid.common.utils.LimitingFrequencyUtils
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*
import java.io.IOException

/**
 * author: weijinsong
 * date: 2020/10/13
 * desc:
 */
class ResponseBodyListener(
    private val mResponseBody: ResponseBody,
    private val mIDownloadListener: IDownloadListener?
) : ResponseBody() {
    private var mBufferedSource: BufferedSource? = null
    override fun contentLength(): Long {
        return mResponseBody.contentLength()
    }

    override fun contentType(): MediaType? {
        return mResponseBody.contentType()
    }

    override fun source(): BufferedSource {
        if (null == mBufferedSource) {
            mBufferedSource = Okio.buffer(source(mResponseBody.source()))
        }
        return mBufferedSource!!
    }

    private fun source(source: Source): Source {
        return object : ForwardingSource(source) {
            var totalBytesRead = MMKVProxy.getLong(
                MMKVProxy.KEY_DOWNLOAD_FILE_FINISH_LENGTH, 0
            )

            @Throws(IOException::class)
            override fun read(sink: Buffer, byteCount: Long): Long {
                val bytesRead = super.read(sink, byteCount)
                totalBytesRead += if (bytesRead != -1L) bytesRead else 0
                if (null != mIDownloadListener && -1L != bytesRead) {
                    try {
                        post {
                            var countLength = mResponseBody.contentLength() + MMKVProxy.getLong(
                                MMKVProxy.KEY_DOWNLOAD_FILE_FINISH_LENGTH, 0
                            )
                            var progress =
                                (totalBytesRead * 100.0 / countLength)
                            if (progress == 100.0) {
                                if (LimitingFrequencyUtils.moreThanLastKeyTime(1000)) {
                                    mIDownloadListener.onComplete(mResponseBody.contentLength())
                                }
                            } else {
                                mIDownloadListener.onProgress(progress)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                return bytesRead
            }
        }
    }

    init {
        if (null != mIDownloadListener) {
            post { mIDownloadListener.onStartDownload(mResponseBody.contentLength()) }
        }
    }
}